import React from 'react';
import PropTypes from 'prop-types';

import "./Typewriter.less";

import * as  CommonUtil from '../../util/CommonUtil';

export default class TypewriterComponent extends React.Component {

    render() {
        const {id, content, containerClassName} = this.props;

        const contentCharLength = CommonUtil.charLength(content);
        let spaceContent = "";
        for (let i = 0; i < contentCharLength / 2; i++) {
            spaceContent += "　";
        }

        return (
            <div id={id} className={containerClassName +' typewriter-container'}>
                {spaceContent}
            </div>
        );
    }

    componentDidUpdate() {
        const {id, content} = this.props;
        if (content) {
            let typewriterContainer = document.getElementById(id);

            let contentArray = content.split("");
            let lastHeight = 0;
            (function loadDiv() {
                if (lastHeight == typewriterContainer.offsetHeight && 0 < typewriterContainer.offsetHeight) {
                    typewriterContainer.style.height = typewriterContainer.offsetHeight + "px";
                    typewriterContainer.innerHTML = "";

                    CommonUtil.delayLoop({
                        "loopFun": (index)=> {
                            typewriterContainer.appendChild(document.createTextNode(contentArray[index]));
                        },
                        "times": contentArray.length,
                        "millisec": 100
                    })

                } else {
                    lastHeight = typewriterContainer.offsetHeight;
                    setTimeout(loadDiv, 1);
                }
            })();
        }
    }

}

TypewriterComponent.propTypes = {
    "id": PropTypes.string.isRequired,
    "content": PropTypes.string,
    "containerClassName": PropTypes.string
}

TypewriterComponent.defaultProps = {};